package com.meaningful.Incurable_diseases;

import cn.hutool.core.util.ZipUtil;
import org.apache.commons.compress.archivers.zip.ZipArchiveEntry;
import org.apache.commons.compress.archivers.zip.ZipArchiveInputStream;

import java.io.*;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipEncodingDetector {

    public static Charset detectZipCharset(File zipFile) {
        List<Charset> tryCharsets = Arrays.asList(
                StandardCharsets.UTF_8,
                Charset.forName("GBK"),
                StandardCharsets.ISO_8859_1
        );

        for (Charset charset : tryCharsets) {
            try (InputStream fis = new FileInputStream(zipFile);
                 BufferedInputStream bis = new BufferedInputStream(fis);
                 ZipArchiveInputStream zis = new ZipArchiveInputStream(bis, charset.name(), true)) {

                boolean success = true;
                ZipArchiveEntry entry;
                while ((entry = zis.getNextZipEntry()) != null) {
                    String name = entry.getName();
                    if (!isProbablyValid(name)) {
                        success = false;
                        break;
                    }
                }

                if (success) {
                    return charset;
                }

            } catch (Exception e) {
                // 解码失败，换下一个编码
                System.err.println(e.getMessage());
            }
        }

        return null; // 都失败，未知编码
    }

    // 简单判断字符串中是否包含乱码（可自行加强逻辑）
    private static boolean isProbablyValid(String str) {
        if (str == null) return false;
        return str.chars().noneMatch(ch -> ch == 0xFFFD || ch == '?');
    }

    public static void main(String[] args) throws IOException {
        File zip = new File("D:\\workspace\\meaningful_java_code\\thinking\\src\\main\\resources\\relocation3.zip");
//        Charset detected = detectZipCharset(zip);
//        if (detected != null) {
//            System.out.println("可能使用的编码是：" + detected.name());
//        } else {
//            System.out.println("无法识别 ZIP 文件编码");
//        }

//        File unzip = ZipUtil.unzip(zip);

        try (ZipInputStream zipIn = new ZipInputStream(new FileInputStream(zip))) {
            ZipEntry entry;
            while ((entry = zipIn.getNextEntry()) != null) {
                // 仅触发 entry.getName() 以测试是否乱码
                System.out.println(entry.getName());
            }
        } catch (IllegalArgumentException e) {
            throw new RuntimeException("ZIP 文件包含非法或非 UTF-8 编码的 entry 名称", e);
        }
    }

}
